package com.framework;

import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

// 日期格式校验规则
class DateFormatRule implements ValidationRule {
    private final String field;
    private final String[] formats;
    
    public DateFormatRule(String field, String... formats) {
        this.field = field;
        this.formats = formats;
    }
    
    @Override
    public ValidationResult validate(Object object) {
        try {
            Field f = object.getClass().getDeclaredField(field);
            f.setAccessible(true);
            Object value = f.get(object);
            
            if (value == null) {
                return ValidationResult.valid();
            }
            
            if (value instanceof String) {
                String dateStr = (String) value;
                for (String format : formats) {
                    try {
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
                        LocalDate.parse(dateStr, formatter);
                        return ValidationResult.valid();
                    } catch (Exception e) {
                        // 尝试下一种格式
                    }
                }
                return ValidationResult.invalid(field, "DATE_FORMAT", 
                        field + "日期格式不正确，支持格式: " + String.join(", ", formats));
            }
            return ValidationResult.valid();
        } catch (Exception e) {
            return ValidationResult.invalid(field, "SYSTEM_ERROR", "系统错误: " + e.getMessage());
        }
    }
}
